package cn.xz.gobang.util

import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.net.ConnectivityManager
import android.net.wifi.WifiManager
import android.os.Build
import android.text.TextUtils
import android.util.DisplayMetrics
import android.util.TypedValue
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import cn.xz.gobang.R
import cn.xz.gobang.base.BaseApplication
import java.net.Inet4Address
import java.net.InetAddress
import java.net.NetworkInterface
import java.util.*

object AppHelper {

    private var VERSIONNAME: String? = null

    //获取当前版本号
    fun getAppVersionName(): String? {
        if (VERSIONNAME != null && VERSIONNAME != "") {
            return VERSIONNAME!!
        }
        try {
            val packageManager = BaseApplication.getContext().packageManager
            val packageInfo =
                packageManager.getPackageInfo(BaseApplication.getContext().packageName, 0)
            VERSIONNAME = packageInfo.versionName
            if (TextUtils.isEmpty(VERSIONNAME)) {
                return ""
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return VERSIONNAME
    }

    //获取当前Code号
    private var VERSIONCODE: String? = null

    @SuppressLint("NewApi")
    fun getAppVersionCode(): String? {
        //   var versionCode = "0"
        if (VERSIONCODE != null && VERSIONCODE != "") {
            return VERSIONCODE!!
        }
        try {
            val packageManager = BaseApplication.getContext().packageManager
            val packageInfo = packageManager.getPackageInfo(BaseApplication.getContext().packageName, 0)
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                VERSIONCODE = packageInfo.longVersionCode.toString()
            } else {
                VERSIONCODE = packageInfo.versionCode.toString()
            }
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return VERSIONCODE
    }


    /**
     * dp转px
     *
     * @param dpVal
     * @return
     */
    fun dp2px(dpVal: Int): Int {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            dpVal.toFloat(),
            BaseApplication.getContext().resources.displayMetrics
        ).toInt()
    }

    /**
     * dp转px
     *
     * @param dpVal
     * @return
     */
    @JvmStatic
    fun dp2px(dpVal: Float): Int {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            dpVal,
            BaseApplication.getContext().resources.displayMetrics
        ).toInt()
    }

    fun getDrawable(id: Int): Drawable?{
        return ContextCompat.getDrawable(BaseApplication.getContext(),id)
    }

    fun getAppWidth(): Int{
        var width = 0
        val metric = DisplayMetrics()
        if (BaseApplication.getCurrentActivity() != null){
            BaseApplication.getCurrentActivity()!!.windowManager.defaultDisplay.getMetrics(metric)
            width = metric.widthPixels // 屏幕宽度（像素）
        }

        return width
    }

    // 获取ip地址
    fun getLocalIpAddress(): String {
        val netManager = BaseApplication.getContext().getSystemService(AppCompatActivity.CONNECTIVITY_SERVICE) as ConnectivityManager
        val info = netManager.activeNetworkInfo

        // 网络是否连接
        return if (info != null && info.isConnected) {
            // wifi类型
            if (info.type == ConnectivityManager.TYPE_WIFI) {
                getWifiIpAddress()
            } else {
                // 其他类型
                getEthIpAddress()
            }
        } else "0.0.0.0"
    }

    // 获取wifi的ip地址
    private fun getWifiIpAddress(): String {
        val wifiManager = BaseApplication.getContext().getSystemService(AppCompatActivity.WIFI_SERVICE) as WifiManager
        val wifiInfo = wifiManager.connectionInfo

        // 获取32位整型IP地址
        val ipAddress = wifiInfo.ipAddress

        //返回整型地址转换成“*.*.*.*”地址
        return String.format(
            "%d.%d.%d.%d",
            ipAddress and 0xff, ipAddress shr 8 and 0xff,
            ipAddress shr 16 and 0xff, ipAddress shr 24 and 0xff
        )
    }

    // 获取有线网络的ip4地址
    private fun getEthIpAddress(): String {
        val infaceName = "eth0"
        val ip = "0.0.0.0"
        try {
            val netInterface: Enumeration<NetworkInterface> =
                NetworkInterface.getNetworkInterfaces()
            while (netInterface.hasMoreElements()) {
                val inface: NetworkInterface = netInterface.nextElement()
                if (!inface.isUp()) {
                    continue
                }

                // eth0 有线网络判断
                if (infaceName != inface.getDisplayName()) {
                    continue
                }
                val netAddressList: Enumeration<InetAddress> = inface.getInetAddresses()
                while (netAddressList.hasMoreElements()) {
                    val inetAddress: InetAddress = netAddressList.nextElement()
                    // 获取IP4地址
                    if (inetAddress is Inet4Address) {
                        return inetAddress.getHostAddress()
                    }
                }
            }
        } catch (e: Exception) {
        }
        return ip
    }
}